/** Smoke.java
 * @version 1.0
 * 
 * @author panther
 * Jayant Pratim Saikia
 * jay.saikia@gmail.com
 * 
 */
package com.panther.awp.android.smoker.activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Currency;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.panther.awp.android.smoker.R;
import com.panther.awp.android.smoker.activities.animate.AnimateScreen;
import com.panther.awp.android.smoker.async.SmokeNowThread;
import com.panther.awp.android.smoker.async.SmokeTimeTrackerTask;
import com.panther.awp.android.smoker.async.SmokeTimerTask;
import com.panther.awp.android.smoker.cache.Cache;
import com.panther.awp.android.smoker.database.AbstractDbAdapter;
import com.panther.awp.android.smoker.database.MyDBWrapper;

public class Smoke extends Activity {

	private Spinner spinner;
	private MyDBWrapper mDBWrapper;
	private Button smokeButton;
	private final SimpleDateFormat outPutFormatDate = new SimpleDateFormat("EEE, dd MMM yyyy");
	private final SimpleDateFormat outPutFormatTime = new SimpleDateFormat("HH:mm z"); 
	private SmokeTimeTrackerTask smokeTimeTrackerTask;
	private ImageView smokeBrandImage;
	private TextView lastSmokeDateText;
	private TextView lastSmokeTimeText;
	private TextView moneySpentText;
	private TextView priceOfBrandText;
	private TextView timesSmokedText;
	private final int INFO_DIALOG = 1001;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.smoketab);
        mDBWrapper = MyDBWrapper.getInstance(getApplicationContext());
        spinner = (Spinner) findViewById(R.id.SpinBrands);
        populatespinner();
        spinner.setOnItemSelectedListener(new MyBrandSelectListner());
        
        smokeButton = (Button) findViewById(R.id.Smokebutton);
        smokeButton.setOnClickListener(smokeClickListner);
        
        smokeBrandImage = (ImageView) findViewById(R.id.smokeBrandImage);
        
        lastSmokeDateText = (TextView) findViewById(R.id.lastSmokeDate);
        lastSmokeTimeText = (TextView) findViewById(R.id.lastSmokeTime);
        moneySpentText = (TextView) findViewById(R.id.moneySpent);
        priceOfBrandText = (TextView) findViewById(R.id.priceOfBrand);
        timesSmokedText = (TextView) findViewById(R.id.timesSmoked);
        
    }
    
	@Override
	protected void onStart() {
		super.onStart();
		//Get Last smoked brand if exists
		Cursor cursor = mDBWrapper.getmTTDbHelper().fetchLatestSmokeEntry(); //Returns one row
		cursor.moveToFirst();
		while(!cursor.isAfterLast()) {
			SpinnerAdapter spinnerAdapter = spinner.getAdapter();
			for (int i = 0; i < spinnerAdapter.getCount(); i++) {
				Cursor dataCursor = (Cursor) spinnerAdapter.getItem(i);
				if(cursor.getLong(cursor.getColumnIndexOrThrow(AbstractDbAdapter.TT_BRAND_ID)) == dataCursor.getLong(dataCursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_PK_ID))) {
					spinner.setSelection(i, true);
				}
			}
			cursor.moveToNext();
		}
		cursor.close();
	}

	private void populatespinner() {
		Cursor cursor = mDBWrapper.getmBTDbHelper().fetchAll();
		startManagingCursor(cursor);
		SpinnerBrandsCursorAdapter spinnerBrandsCursorAdapter = new SpinnerBrandsCursorAdapter(getApplicationContext(), cursor);
		spinner.setAdapter(spinnerBrandsCursorAdapter);
	}
	
	private OnClickListener smokeClickListner = new OnClickListener() {
		
		public void onClick(View v) {
			if(spinner.getChildCount() > 0) {
				
				SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Smoke.this);
		        String currencyCode = prefs.getString("yCurrency", Currency.getInstance(Locale.getDefault()).getCurrencyCode());
				
				Long brandId = spinner.getSelectedItemId();
				String brandName = ((Cursor)spinner.getSelectedItem()).getString(((Cursor)spinner.getSelectedItem()).getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND));
				float cost = ((Cursor)spinner.getSelectedItem()).getFloat(((Cursor)spinner.getSelectedItem()).getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND_PRICE));
				
				SmokeNowThread thread = new SmokeNowThread(getApplicationContext(), brandId);
				thread.start();
				
				final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
				final Notification notification = new Notification(R.drawable.icon, "Smoking " + brandName, System.currentTimeMillis());
				notification.flags |= Notification.FLAG_AUTO_CANCEL;
				Intent notificationIntent = new Intent();
				PendingIntent pendingIntent = PendingIntent.getActivity(Smoke.this, 0, notificationIntent, 0);
				notification.setLatestEventInfo(Smoke.this, "Smoked " + brandName, "It cost you " + Currency.getInstance(currencyCode).getSymbol(Locale.getDefault()) + " " + cost + ".", pendingIntent);
				notificationManager.notify(666, notification);
	
				new SmokeTimerTask(getApplicationContext()).execute();
				smokeTimeTrackerTask = new SmokeTimeTrackerTask(getApplicationContext(), smokeButton);
		        smokeTimeTrackerTask.execute();
		        
		        Intent animationIntent = new Intent(getApplicationContext(), AnimateScreen.class);
		        animationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				animationIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
				animationIntent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
		        startActivity(animationIntent);
		        
		        lastSmokeDateText.setText(R.string.now);
		        lastSmokeTimeText.setText(R.string.now);
		        moneySpentText.setText("");
		        timesSmokedText.setText(String.valueOf((Integer.parseInt(timesSmokedText.getText().toString()) + 1)));
			} else {
				Toast toast = Toast.makeText(Smoke.this, R.string.empty_brand, Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM, 0, 20);
				toast.show();
			}
		}
	};
	
	private class MyBrandSelectListner implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
			Cursor cursor = (Cursor) parent.getItemAtPosition(pos);
			startManagingCursor(cursor);
			float price = cursor.getFloat(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND_PRICE));
			int no_of_ciggs = cursor.getInt(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_NO_OF_CIGGS));
			float money_spent = price * (float)no_of_ciggs;
			Long brandId = cursor.getLong(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_PK_ID));
			priceOfBrandText.setText(String.valueOf(price));
			timesSmokedText.setText(String.valueOf(no_of_ciggs));
			if(no_of_ciggs > 0) {
				Cursor anotherCursor = mDBWrapper.getmTTDbHelper().fetchLatestSmokeEntry(brandId);
				anotherCursor.moveToFirst();
				String dateSmokedStr = anotherCursor.getString(anotherCursor.getColumnIndexOrThrow(AbstractDbAdapter.TT_DATETIME));
				try {
					Date date = AbstractDbAdapter.DATE_FORMAT.parse(dateSmokedStr);
					lastSmokeDateText.setText(outPutFormatDate.format(date));
					lastSmokeTimeText.setText(outPutFormatTime.format(date));
				} catch (IllegalArgumentException e) {
				} catch (ParseException e) {
				}
				anotherCursor.close();
				moneySpentText.setText(String.valueOf(money_spent) + " Bucks");
			} else {
				lastSmokeDateText.setText(R.string.not_Smoked);
				lastSmokeTimeText.setText(R.string.not_Smoked);
				moneySpentText.setText("0.00 Bucks");
			}
			String brandUri = cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_IMAGE_URI));
			if(brandUri.equals("NO_IMAGE")) {
				smokeBrandImage.setImageResource(R.drawable.icon);
			} else {
				smokeBrandImage.setImageBitmap(Cache.getCacheFile(brandUri));
			}
		}

		public void onNothingSelected(AdapterView<?> arg0) {
			
		}
		
	}
	
	private class SpinnerBrandsCursorAdapter extends CursorAdapter {
		
		LayoutInflater layoutInflater;

		public SpinnerBrandsCursorAdapter(Context context, Cursor c) {
			super(context, c);
			layoutInflater = LayoutInflater.from(context);
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			String brandUri = cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_IMAGE_URI));
			String brandName = cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND));
			if(!brandUri.equals("NO_IMAGE")) {
				((ImageView) view.findViewById(R.id.smokeIconDropDown)).setImageBitmap(Cache.getCacheFile(brandUri));
			} else {
				((ImageView) view.findViewById(R.id.smokeIconDropDown)).setImageResource(R.drawable.icon);
			}
			((CheckedTextView) view.findViewById(R.id.checkedTextView)).setText(brandName);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			return layoutInflater.inflate(R.layout.brandsdropdownrow, parent, false);
		}
		
	}
	
	// Inflating Menu on menu press and do on select row 
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.smoketabmenu, menu);
	    return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		  case R.id.settings_menuItem:
					Intent intent = new Intent(this, Settings.class);
					startActivity(intent);
					return super.onOptionsItemSelected(item);
		  case R.id.info_menuItem:
				  showDialog(INFO_DIALOG);
		  default:
			  		return super.onOptionsItemSelected(item);
		  }
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder;
		AlertDialog alertDialog;
		Context mContext = Smoke.this;
		LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
		switch (id) {
			case INFO_DIALOG:
				View layout = inflater.inflate(R.layout.info_dialog, (ViewGroup) findViewById(R.id.info_dialog_id));
				builder = new AlertDialog.Builder(mContext);
				builder.setView(layout);
				alertDialog = builder.create();
				alertDialog.setTitle("Smoker App");
				break;
			default:
				alertDialog = null;
		}
		return alertDialog;
	}

	// Cancel or resume timer tasks after leaving or comming to this screen ...
	@Override
	protected void onPause() {
		super.onPause();
		if(smokeTimeTrackerTask != null) {
			smokeTimeTrackerTask.cancel(true);	
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		smokeTimeTrackerTask = new SmokeTimeTrackerTask(getApplicationContext(), smokeButton);
        smokeTimeTrackerTask.execute();
	}
	
}